package com.learn.service.impl;

import com.learn.service.SendEmailService;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: learn-parent
 * @description
 * @author: luffy
 * @create: 2020-09-16 23:02
 */
@Service
public class SendEmailServiceImpl implements SendEmailService {
    @Value("${email.username}")
    private String username;


    @Value("${email.password}")
    private String password;


    @Value("${email.name}")
    private String name;


    @Value("${email.subject}")
    private String subject;


    @Value("${email.hostname}")
    private String hostname;

    @Override
    public boolean sendEmail(String emailAddress, String code) {
        System.out.println(username+name+subject+hostname);
        if (StringUtils.isEmpty(emailAddress) || StringUtils.isEmpty(code)) {
            System.out.println("邮箱或验证码为空");
        }
        HtmlEmail email = new HtmlEmail();
        List<String> list = new ArrayList<String>();
        list.add(emailAddress);
        String[] tos = list.toArray(new String[list.size()]);
        email.setHostName(hostname);
        email.setCharset("UTF-8");
        try {
            email.addTo(tos);
            email.setFrom(username, name);
            email.setAuthentication(username, password);
            email.setSubject(subject);
            email.setHtmlMsg("您好 " + emailAddress + " \n" +
                    "欢迎注册，请将验证码：" + code +",10分钟内有效 ！");
            email.send();
            return true;
        } catch (EmailException e) {
            e.printStackTrace();
            return false;
        }

    }
}
